<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="700px" :close-on-click-modal="false"
    :before-close="handleClose">
    <div class="form">
      <!-- 表单输入元件 ----------------------------------------------------------------------------------------->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="rule-form">
        <el-form-item label="设备名称" prop="equipmentAccountId">
          <el-select v-if="!isUpdateForm" v-model="ruleForm.equipmentAccountId" filterable placeholder="请选择设备">
            <el-option v-for="item in equipmentAccountList" :key="item.equipmentAccountId"
              :label="item.equipmentName + '（' + item.equipmentNum + '）'" :value="item.equipmentAccountId + ''" />
          </el-select>
          <el-input v-if="isUpdateForm" disabled v-model="ruleForm.equipmentAccountId" />
        </el-form-item>

        <el-form-item v-if="!isUpdateForm" label="异常项目" prop="abnormalProject">
          <el-select v-model="ruleForm.abnormalProject" multiple placeholder="请选择异常项目">
            <el-option v-for="item in DictionaryList" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="isUpdateForm" label="异常项目" prop="abnormalProjects">
          <el-input disabled v-model="ruleForm.abnormalProjects" />
        </el-form-item>

        <el-form-item label="描述" prop="describe">
          <el-input v-if="!isUpdateForm" type="textarea" placeholder="请输入描述" v-model="ruleForm.describe" maxlength="50"
            show-word-limit>
          </el-input>
          <el-input v-if="isUpdateForm" disabled v-model="ruleForm.describe" />
        </el-form-item>

        <el-divider v-if="!isUpdateForm">附件：异常图片/异常视频</el-divider>

        <el-form-item label="异常图片">
          <Image-upload :value='ruleForm.equipmentRepairImages'
            :limit="isUpdateForm ? ruleForm.equipmentRepairImages.length : 5"
            :isDisabled="isUpdateForm ? ['update', 'delete'] : []" @input="handleInput" />
        </el-form-item>

        <el-form-item label="异常视频">
          <Video-upload v-if="!isUpdateForm" ref="videoUpload" v-model="ruleForm.video"
            @returnBack="handleReturnBack" />
          <div v-if="isUpdateForm">
            <video v-if="ruleForm.video" ref="videoPlay" :src="ruleForm.video" width="290" height="203"
              style="background-color: black" controls="controls">
              您的浏览器不支持视频播放
            </video>
            <div v-else>-</div>
          </div>
        </el-form-item>

        <el-form-item label="备注" v-if="isUpdateForm">
          <el-input type="textarea" placeholder="请输入备注" v-model="ruleFormDetail.remark" maxlength="200"
            show-word-limit />
        </el-form-item>
      </el-form>
      <!-- ----------------------------------------------------------------------------------------------------->
    </div>
    <div class="dialog_footer">
      <el-button type="primary" @click="handleConfirm">提交</el-button>
      <!-- <el-button  @click="handleReset">重置</el-button> -->
      <el-button @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
/** 远程添加，修改，获取单个详性接口，获取selector下拉列表的接口，以及时间转换工具函数等 ------------------------------------------------- */
import { listEquipmentAccount, listDictionary, add, listDetail, update } from '@/api/maintenance/management/equipmentAssembly.js'
import UploadImage from '@/components/upload/index.vue'
/** ------------------------------------------------------------------------------------------------------------------------------- */

/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  equipmentAccountId: null, //设备台账ID
  abnormalProject: [], //异常项目
  describe: "", //描述
  equipmentRepairImages: [], //图片集合
  video: "" //视频
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */
function processRuleForm (ruleForm) {
  const images = ruleForm.equipmentRepairImages.map(item => {
    return {
      image: item.url
    }
  })
  const str = ruleForm.abnormalProject.join(',')
  const data = Object.assign({}, ruleForm)
  data.abnormalProject = str
  data.equipmentRepairImages = images
  return data
}

export default {
  name: 'Form',
  components: {
    UploadImage
  },
  data () {
    return {
      dialogVisible: false,
      ruleForm: Object.assign({}, ruleForm),
      isUpdateForm: false,
      dialogTitle: '添加供应商',
      DictionaryList: [],
      equipmentAccountList: [],//设备名称接收数组
      ruleFormDetail: { //已消除的提交数据
        remark: '',
        equipmentRepairId: ''
      },
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        equipmentAccountId: [
          { required: true, message: '请选择设备', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        abnormalProject: [
          { required: true, message: '请选择异常', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        equipmentRepairImages: [
          { required: true, message: '请上传异常图片', trigger: 'change' }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
      }
      /** ----------------------------------------------------------------------------------------------------------------------------- */
    }
  },
  methods: {

    // 设备名称和异常项目数据接口---------------------------------------------
    async handleListType () {
      const { data: res1 } = await listEquipmentAccount({ 'params[userStatuses]': '0,1,2,4', 'params[statuses]': '0,3' })//设备名称
      const { data: res2 } = await listDictionary({ dictType: 'abnormal_project', status: 0 })//异常项目，字典单位
      this.equipmentAccountList = res1
      this.DictionaryList = res2
    },
    // 上传图片处理方法-----------------
    handleInput (val) {
      this.ruleForm.equipmentRepairImages = val
    },
    // 上传视频处理方法--------------------
    handleReturnBack (val) {
      this.ruleForm.video = val
    },
    // 打开表单对话框
    openDialog (id = null) {
      this.handleListType()
      if (id) {
        listDetail(id).then(res => {
          this.isUpdateForm = true
          this.dialogTitle = '已消除'
          /** 消除时的表单参数赋值,值需要一个必传id或者备注 --------------------------------------------------------------------------------------------------------------------- */
          this.ruleFormDetail.equipmentRepairId = res.data.equipmentRepairId
          // -----------------------------------------已消除展示的数据，与表单无关 -------------------------------------
          this.ruleForm.equipmentAccountId = res.data.eaPartInfoVo.equipmentName + '（' + res.data.eaPartInfoVo.equipmentName + '）'
          // this.ruleForm.abnormalProject = res.data.abnormalProjectName
          this.$set(this.ruleForm, 'abnormalProjects', res.data.abnormalProjectName)
          this.ruleForm.describe = res.data.describe
          this.ruleForm.equipmentRepairImages = res.data.equipmentRepairImages.map(item => item.image)
          this.ruleForm.video = res.data.video
          this.dialogVisible = true
        })
      } else {
        this.isUpdateForm = false
        this.dialogTitle = '添加报修设备'
        this.dialogVisible = true
      }
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleFormDetail);
          if (this.isUpdateForm) {
            update(this.ruleFormDetail).then((res) => {
              this.$message({
                message: '消除成功',
                type: 'success'
              })
              this.handleClose()
              this.$emit('submit_success')
            })
          } else {
            if (this.ruleForm.equipmentRepairImages.length || this.ruleForm.video) {
              const data = processRuleForm(this.ruleForm)
              add(data).then((res) => {
                this.$message({
                  message: '创建成功',
                  type: 'success'
                })
                this.handleClose()
                this.$emit('submit_success')
              })
            } else {
              this.$message({
                message: '请上传异常图片或者异常视频！',
                type: 'error'
              })
            }
          }
        } else {
          this.$message({
            message: '数据验证不通过，检查输入表单',
            type: 'error'
          })
          return false
        }
      })
    },
    /** ---------------------------------------------------------------------------------------------------------------------------------------- */
    // 关闭窗口，重置表单
    handleClose () {
      if (!this.isUpdateForm) {
        this.$refs.videoUpload.clearVideo() //删除视频
      }
      this.ruleForm = Object.assign({}, ruleForm)
      this.$nextTick(function () {
        this.$refs['ruleForm'].clearValidate()
      });
      this.dialogVisible = false
    },
    handleConfirm () {
      this.submitForm('ruleForm')
    },
  }
}
</script>
<style lang="scss" scoped>
.form {
  width: 500px;
  margin-left: auto;
  margin-right: auto;

  .inventory {
    display: flex;
  }
}

::v-deep .el-input-number__decrease {
  display: none;
}

::v-deep .el-input-number__increase {
  display: none;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-input-number {
  width: 100%;
}

.dialog_footer {
  display: flex;
  justify-content: center;
}
</style>
